﻿namespace Api.Filters;

/// <summary>
/// XSS过滤
/// </summary>
public class XSSFilter : ActionFilterAttribute
{
    /// <summary>
    /// 重写执行方法
    /// </summary>
    /// <param name="context"></param>
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // context.HttpContext.Response.Headers["Access-Control-Allow-Origin"] = "*";
        //获取参数集合
        var ps = context.ActionDescriptor.Parameters;
        if (ps.Count() == 0)
        {
            return;
        }
        //遍历参数集合
        foreach (var p in ps)
        {
            if (context.ActionArguments.ContainsKey(p.Name))
            {
                if (p.ParameterType.IsGenericType)
                {
                    continue;
                }
                if (context.ActionArguments[p.Name] != null)
                {
                    //当参数是str
                    if (p.ParameterType.Equals(typeof(string)))
                    {
                        context.ActionArguments[p.Name] = XSSHelper.XssFilter(context.ActionArguments[p.Name].ToString());
                    }
                    else if (p.ParameterType.IsClass)//当参数是一个实体
                    {
                        PostModelFieldFilter(p.ParameterType, context.ActionArguments[p.Name]);
                    }
                }
            }
        }
    }
    /// <summary>
    /// 遍历实体字符串属性
    /// </summary>
    /// <param name="type"></param>
    /// <param name="obj"></param>
    /// <returns></returns>
    private object PostModelFieldFilter(Type type, object obj)
    {
        if (obj != null)
        {
            foreach (var item in type.GetProperties())
            {
                if (item.PropertyType.IsGenericType)
                {
                    continue;
                }
                if (item.GetValue(obj) != null)
                {
                    //当参数是str
                    if (item.PropertyType.Equals(typeof(string)))
                    {
                        string value = item.GetValue(obj).ToString();
                        item.SetValue(obj, XSSHelper.XssFilter(value));
                    }
                    else if (item.PropertyType.IsClass)
                    {
                        // item.SetValue(obj, PostModelFieldFilter(item.PropertyType, item.GetValue(obj)));
                    }
                }
            }
        }
        return obj;
    }
}
